from google.appengine.ext import db
import random, string

class _File(db.Model):
    #id = key.name # store identifier at key.name
    filename = db.StringProperty()
    content = db.BlobProperty()
    
    @property
    def file_id(self):
        return self.key().name()
    
    @classmethod
    def create_file(cls, filename, content):
        return db.run_in_transaction(cls._create_file, filename, content)
    
    @classmethod
    def _create_file(cls, filename, content):
        key = cls.randomString()
        while(cls.get_file_by_id(key)):
            key = cls.randomString()
        f = cls(key_name=key, filename=filename, content=content)
        f.put()
        return f
    
    @classmethod
    def get_file_by_id(cls, id):
        return cls.get_by_key_name(key_names=id)

    @classmethod
    def randomString(cls, length=16):
        return ''.join((random.choice(string.ascii_letters + string.digits) for _ in range(length)))
